package com.tongjie.hotelbooking.controller.common;

import com.tongjie.hotelbooking.http.BaseResponse;
import com.tongjie.hotelbooking.im.websocket.WebSocketEndpoint;
import com.tongjie.hotelbooking.security.user.CurrentUserInfo;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/users")
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public class SecuredUsersController {

    @GetMapping("/current")
    public BaseResponse<CurrentUserInfo> getCurrent(@AuthenticationPrincipal final CurrentUserInfo user) {
        return BaseResponse.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<?> logout(@AuthenticationPrincipal final CurrentUserInfo user) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        WebSocketEndpoint.closeConnection(user.getId());
        request.getSession().invalidate();
        return BaseResponse.success();
    }

}
